import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function GET() {
  try {
    // 构建获取所有反馈并关联用户信息的 SQL 语句
    const sql = `
      SELECT 
        f.feedbackId, 
        f.openId, 
        f.content AS feedbackContent, 
        f.FBTime AS feedbackTime, 
        u.uName, 
        u.avatarUrl
      FROM 
        feedback f
      LEFT JOIN 
        user u ON f.openId = u.openId
      ORDER BY 
        f.FBTime DESC;
    `;

    // 使用 $queryRawUnsafe 执行 SQL 语句
    const feedbacks = await prisma.$queryRawUnsafe(sql);

    // 格式化数据以匹配前端期望的结构
    const formattedFeedbacks = feedbacks.map((feedback: any) => ({
      feedbackId: feedback.feedbackId,
      openId: feedback.openId,
      feedbackContent: feedback.feedbackContent,
      feedbackTime: feedback.feedbackTime,
      userName: feedback.uName,
      userAvatar: feedback.avatarUrl,
    }));

    return NextResponse.json(
      { feedbacks: formattedFeedbacks },
      { status: 200 }
    );
  } catch (error) {
    console.error("获取反馈数据失败:", error);
    return NextResponse.json({ error: "获取反馈数据失败" }, { status: 500 });
  }
}

export async function PATCH(request: Request) {
  try {
    const body = await request.json();
    const { feedbackId } = body;

    if (!feedbackId) {
      return NextResponse.json({ error: "反馈ID不能为空" }, { status: 400 });
    }

    // 这里由于没有 feedbackState 列，无法进行更新操作，需要根据实际需求决定如何处理
    // 暂时返回错误信息
    return NextResponse.json(
      { error: "反馈表中不存在 feedbackState 列，无法更新状态" },
      { status: 500 }
    );
  } catch (error) {
    console.error("更新反馈状态失败:", error);
    return NextResponse.json({ error: "更新反馈状态失败" }, { status: 500 });
  }
}
